package HospitalDepartment

import (
	"ToolLibray/jwtx"
	"context"
	"fmt"
	"property_api/utils/result"
	"property_api/utils/tree"
	"property_service/property_service"

	"github.com/zeromicro/go-zero/core/logx"
	"property_api/internal/svc"
	"property_api/internal/types"
)

type (
	PagesLogic struct {
		logx.Logger
		ctx    context.Context
		svcCtx *svc.ServiceContext
	}
	dept struct {
		types.HospitalDepartment
		Children []tree.NodeWithChildren `json:"children"`
	}
)

func (d *dept) GetID() int64 {
	//TODO implement me
	return d.ID
}

func (d *dept) GetParentID() int64 {
	//TODO implement me
	return d.ParentID
}

func (d *dept) GetChildren() []tree.NodeWithChildren {
	//TODO implement me
	return d.Children
}

func (d *dept) SetChildren(children []tree.NodeWithChildren) {
	d.Children = children
}

func NewPagesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PagesLogic {
	return &PagesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// Pages 查询医院科室的分页逻辑
func (l *PagesLogic) Pages(req *types.HospitalDepartmentPageReq) (resp *types.PageRes, err error) {
	// 设置租户ID，从上下文中获取
	tenantID := jwtx.GetUserTenantId64(l.ctx)
	fmt.Print("fmp:", req)
	fmt.Print("Tree:", req.Tree)
	// 构建查询条件对象
	where := &property_service.HospitalDepartment{
		ID:                req.ID,                // 记录ID
		ParentID:          req.ParentID,          // 父级ID
		ParentCode:        req.ParentCode,        //父级编码
		ParentLs:          req.ParentLs,          // 父级列表
		DepartmentCode:    req.DepartmentCode,    // 科室编号
		HisDepartmentCode: req.HisDepartmentCode, // HIS科室编码
		Name:              req.Name,              // 科室名称
		DepartmentType:    req.DepartmentType,    // 科室类型
		PinyinCode:        req.PinyinCode,        // 拼音简码
		Director:          req.Director,          // 科室负责人
		MaintenanceAuto:   req.MaintenanceAuto,   // 维修自动处理
		Status:            req.Status,            // 状态
		Remark:            req.Remark,            // 备注
		StockID:           req.StockID,           // 仓库ID
		TenantID:          tenantID,              // 租户ID
	}
	// 调用服务层方法，查询医院科室记录的分页数据
	// 服务层方法 HospitalDepartmentPage 会处理实际的数据库查询操作
	data, err := l.svcCtx.BasicService.HospitalDepartmentPage(l.ctx, &property_service.HospitalDepartmentPageReq{
		Page:  req.Page,  // 当前页码
		Limit: req.Limit, // 每页条数
		Where: where,     // 查询条件
	})

	if req.Tree != 1 {
		// 返回分页数据的响应
		return result.SucPage(data, types.HospitalDepartment{}).PageEd()
	}
	// 返回分页数据的响应
	return result.SucPage(data, dept{}, func(value interface{}) interface{} {
		data := value.([]*dept)
		return tree.MakeTreeByID(func() []tree.NodeWithChildren {
			convertedNodes := make([]tree.NodeWithChildren, 0)
			for _, category := range data {
				convertedNodes = append(convertedNodes, category)
			}
			return convertedNodes
		}())
	}).PageEd()
}
